package com.group525.cloudef.service.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.group525.cloudef.common.Message;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/socket/{username}")
@Component
public class WebSocketServer {
    private static final Map<String, Session> sessionmap=new ConcurrentHashMap<>();

    /**
     * 打开连接 并且发送广播消息
     * @param session
     * @param username
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username){
        sessionmap.put(username,session);
        sendAllMessage(setUserList());
        System.out.format("username:%S,建立了连接\n",username);
    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username){
        sessionmap.remove(username);
        sendAllMessage(setUserList());
        System.out.format("username:%S掉线了",username);
    }
    @OnMessage
    public void OnMessage(Session session,String message, @PathParam("username") String username){
        //有个人发来了信息 到了中转站
        System.out.println("收到消息了"+message);
        this.sendMessage(session,message);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(error.getMessage());
    }

    private void sendMessage(Session session,String message){
        try {
            System.out.println("sendMessage"+session.getId()+"----"+message);
            System.out.println(JSON.parse(message));
            Message message1 = JSONObject.parseObject(message, Message.class);
            String to = message1.getTo();
            Session session1 = sessionmap.get(to);
            session1.getBasicRemote().sendText(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void sendAllMessage(String message) {
        try {
            for (Session session : sessionmap.values()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String setUserList(){
        ArrayList<String> list = new ArrayList<>();
        for(String key:sessionmap.keySet()){
            list.add(key);
        }
        Message message = new Message();
        message.setUserLists(list);
        return JSON.toJSONString(message);
    }

}